import Taro from '@tarojs/taro';
import { Component } from 'react';
import dayjs from 'dayjs'
import { View, PickerView, PickerViewColumn } from '@tarojs/components';
import './index.scss'
// import PropTypes from 'prop-types';
let defaultTime = new Date().getFullYear()
class RangeHourPicker extends Component {

    state = {
        pickVal: [],
        range: {},
        checkObj: {},
        values: null
    }

    UNSAFE_componentWillMount() {
      this.initData()
    }

    componentDidMount() { 
      
    }

    componentWillUnmount() { }

    componentDidShow() { }

    componentDidHide() { }

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.value !== this.state.values) {
            // this.initData();
            this.setState({
                values: prevProps.value,
            }, () => {
                this.initData();
            })
        }
    }

    formatNum(n) {
      return (Number(n) < 10 ? '0' + Number(n) : Number(n) + '');
    }
    formatHour(n) {
      return (Number(n) < 10 ? `0${Number(n)}:00` : `${Number(n)}:00`);;
    }

    checkValue = (value) => {
        let strReg = /^\d{2}:00$/, example = "08:00";
        if (!strReg.test(value[0]) || !strReg.test(value[1])) {
            console.log(new Error("请传入与mode匹配的value值，例[" + example + "," + example + "]"))
        }
        return strReg.test(value[0]) && strReg.test(value[1]);
    }

    resetToData = (fmonth, fday, tyear, tmonth) => {
        let range = this.state.range;
        let tmonths = [], tdays = [];
        let yearFlag = tyear != range.tyears[0];
        let monthFlag = tyear != range.tyears[0] || tmonth != range.tmonths[0];
        let ttotal = new Date(tyear, tmonth, 0).getDate();
        for (let i = yearFlag ? 1 : fmonth * 1; i <= 12; i++) {
            tmonths.push(this.formatNum(i))
        }
        for (let i = monthFlag ? 1 : fday * 1; i <= ttotal; i++) {
            tdays.push(this.formatNum(i))
        }
        return {
            tmonths,
            tdays
        }
    }
    getData = (dVal) => {
        let value = dVal;
        let fhours = [], thours = [], pickVal = [];
        for (let i = this.props.startHour; i <= this.props.endHour; i++) {
            fhours.push(this.formatHour(i));
        };
        let resetHour = this.resetHour(value[0], value[2]);
            thours = resetHour.thours;
        pickVal = [
            fhours.indexOf(value[0]) == -1 ? 0 : fhours.indexOf(value[0]),
            0,
            thours.indexOf(value[2]) == -1 ? 0 : thours.indexOf(value[2]),
        ];
        return {
            fhours,
            thours,
            pickVal
        }
    }

    getDval = () => {
        let value = this.props.value;
        let dVal = null;
        let aDate = new Date();
        let fhour = '07:00';
        let thour = '07:00';
        if (value && value.length > 0) {
            let flag = this.checkValue(value);
            if (!flag) {
                dVal = [fyear,  "-", tyear]
            } else {
                dVal = [...value[0].split("-"), "-", ...value[1].split("-")];
            }
        } else {
            dVal = [fhour, "-", thour]
        }
        return dVal;
    }

    initData = () => {
        let range = [], pickVal = [];
        let result = "", full = "", obj = {};
        let dVal = this.getDval();
        let dateData = this.getData(dVal);
        let fhours = [], thours = [];
        let  fhour, thour;
        pickVal = dateData.pickVal;
        fhours = dateData.fhours;
        thours = dateData.thours;
        range = {
            fhours,
            thours,
        }
        fhour = range.fhours[pickVal[0]];
        thour = range.thours[pickVal[2]];
        obj = {
            fhour,
            thour
        }
        result = `${fhour + '至' + thour }`;
        full = `${fhour + '-' + thour }`;
        this.setState({
            range,
            checkObj: obj
        })
        Taro.nextTick(() => {
            this.setState({
                pickVal
            })
        });
        this.props.change({
            result: result,
            value: full,
            obj: obj
        })
    }

    handlerChange = (e) => {
        let arr = [...e.detail.value];
        let result = "", full = "", obj = {};
        let checkObj = this.state.checkObj;
        let xDate = new Date().getTime();
        let range = this.state.range;
        let fhour = range.fhours[arr[0]] || range.fhours[range.fhours.length - 1];
        let thour = range.thours[arr[2]] || range.thours[range.thours.length - 1];
        let resetHour = this.resetHour(fhour, thour)
        if (fhour != checkObj.fhour ) {
          arr[2] = 0
          range.thours = resetHour.thours;
          thour = range.thours[arr[2]];
        }
        result = `${fhour + '至' + thour }`;
        full = `${fhour + '-' + thour }`;
        obj = {
            fhour,
            thour
        }
        this.setState({
            checkObj: obj
        })
        // Taro.nextTick(() => {
            this.setState({
                pickVal: arr
            })
        // });
        console.log(obj, arr);
        this.props.change({
            result: result,
            value: full,
            obj: obj
        })
    }
    resetHour = (fhour, thour) => {
      let fhours = [], thours = [];
      let startHour = this.props.startHour;
      // let ftotal = new Date(fyear, fmonth, 0).getDate();
      // let ttotal = new Date(tyear, tmonth, 0).getDate();
      // for (let i = this.props.startHour; i <= this.props.endHour; i++) {
      //     fhours.push(this.formatHour(i));
      // };
      for (let i = Number(fhour.replace(/:00/, "")); i <= this.props.endHour; i++) {
          thours.push(this.formatHour(i));
      };
      return {
          // fhours,
          thours,
      }
    }

    render() {
        const { pickVal, range }=this.state
        return (
            <View className='w-picker-view'>
                <PickerView className="d-picker-view"  indicatorClass="active-indicator" value={pickVal} onChange={this.handlerChange}>
                    <PickerViewColumn className="w-picker-flex2">
                        {
                            range.fhours.map((item, index) => {
                                return (<View className="w-picker-item" key={index}>{item}</View>)
                            })
                        }
                    </PickerViewColumn>
                    <PickerViewColumn className="w-picker-flex1">
                        <View className="w-picker-item">至</View>
                    </PickerViewColumn>
                    <PickerViewColumn className="w-picker-flex2">
                        {
                            range.thours.map((item, index) => {
                                return (<View className="w-picker-item" key={index}>{item}</View>)
                            })
                        }
                    </PickerViewColumn>
                </PickerView>
            </View>
        )
    }
}

// RangePicker.PropTypes = {
//     itemHeight: PropTypes.string,
//     value: PropTypes.oneOfType([
//         PropTypes.string,
//         PropTypes.array
//     ]),
//     current: PropTypes.bool,
//     startYear: PropTypes.oneOfType([
//         PropTypes.string,
//         PropTypes.number,
//     ]),
//     endYear: PropTypes.oneOfType([
//         PropTypes.string,
//         PropTypes.number,
//     ])
// }
RangeHourPicker.defaultProps = {
    // itemHeight: "color: #FFA409; border-color: red;",
    value: ['12:00', '14:00'],
    startHour: 7,
    endHour: 22,
    current: false,
    startYear: 1970,
    endYear: defaultTime
}

export default RangeHourPicker
